package hot100;

public class Solution162 {
    public int findPeakElement1(int[] nums) {
        for (int i = 0; i < nums.length; i++) {
            int left = Integer.MIN_VALUE;
            int right = Integer.MIN_VALUE;
            if (i > 0) {
                left = nums[i - 1];
            }
            if (i < nums.length - 1) {
                right = nums[i + 1];
            }
            if (nums[i] > left && nums[i] > right) {
                return i;
            }
        }
        return -1;
    }

    public int findPeakElement(int[] nums) {
        if (nums.length == 1) {
            return 0;
        }
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = (left + right) / 2;
            if (isPeak(nums, mid)) {
                return mid;
            } else if (mid < nums.length - 1 && nums[mid] < nums[mid + 1]){
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    public boolean isPeak(int nums[], int index) {
        if (index == 0) {
            return nums[index] > nums[index + 1];
        }

        if (index == nums.length - 1) {
            return nums[index] > nums[index - 1];
        }

        return nums[index] > nums[index + 1] && nums[index] >  nums[index - 1];
    }

    public static void main(String[] args) {
        Solution162 solution162 = new Solution162();
        solution162.findPeakElement(new int[]{2,1});
    }
}
